﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Business.Abstract;
using Business.Service;
using Domain.Entity;
using PresentationMVC.Models;
using Business.Common;

namespace PresentationMVC.Controllers
{
    public class StaffController : Controller
    {

        #region Actions
        /// <summary>
        /// Load the Staff main page
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            Session.Remove(Constants.STAFF_SEARCH_SESSION);
            StaffDataModel model = GetStaffDataModel();
            return View(model);
        }

        /// <summary>
        /// Load the staff in the form to update the details
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(long id)
        {
            IStaffService srv = new StaffServiceImpl();
            Staff staff = srv.GetStaffById(id);
            staff.InitialEmail = staff.Email;
            StaffDataModel model = GetStaffDataModel(staff);
            return View("Index", model);
        }

        /// <summary>
        /// Delete the staff 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Delete(long id)
        {
            IStaffService srv = new StaffServiceImpl();
            Staff staff = srv.GetStaffById(id);
            srv.DeleteStaff(staff);

            ViewData["DELETE_MSG"] = "Successsfully deleted the record.";

            this.ViewData.Model = GetStaffDataModel();
            return PartialView("StaffGridPartial");
        }

        [HttpGet]
        public ActionResult ReloadGrid()
        {
            StaffDataModel model = GetStaffDataModel();
            this.ViewData.Model = model;
            return PartialView("StaffGridPartial", model);
        }

        [HttpPost]
        public ActionResult GridviewSearch(StaffDataModel model)
        {
            Session[Constants.STAFF_SEARCH_SESSION] = model.StaffSearch;
            this.ViewData.Model = GetStaffDataModel();
            return PartialView("StaffGridPartial");
        }

        /// <summary>
        /// Save the staff details
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(StaffDataModel model)
        {
            return SaveOrUpdate(model);
        }

        [HttpGet]
        public JsonResult EmailAvailable(StaffDataModel model)
        {
            if (model.Staff.Email != model.Staff.InitialEmail)
            {
                IStaffService srv = new StaffServiceImpl();
                Staff staff = srv.GetStaffByEmail(model.Staff.Email);
                if (staff == null)
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(string.Format("{0} already exist", Request.QueryString["Staff.Email"]), JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }

        }
        #endregion

        #region Private Methods
        private StaffDataModel GetStaffDataModel()
        {
            return GetStaffDataModel(null);
        }

        private StaffDataModel GetStaffDataModel(Staff staff)
        {
            IStaffService srv = new StaffServiceImpl();
            IList<Staff> lstStaff = new List<Staff>();
            if (Session[Constants.STAFF_SEARCH_SESSION] == null)
            {
                lstStaff = srv.GetAllStaffs();
            }
            else
            {
                StaffDataModel sdm = new StaffDataModel();
                sdm.StaffSearch = Session[Constants.STAFF_SEARCH_SESSION] as StaffSearchModel;
                lstStaff = srv.GetAllStaffs(sdm.StaffSearch.SearchBy, sdm.StaffSearch.Value);
            }
            StaffDataModel model = new StaffDataModel();
            model.Staff = staff == null ? new Staff() : staff;
            model.AllStaff = lstStaff;
            return model;
        }



        /// <summary>
        /// Base on the staff object it create a new staff record or update already existing record.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private ActionResult SaveOrUpdate(StaffDataModel model)
        {
            Staff staff = model.Staff;
            IStaffService staffSrv = new StaffServiceImpl();

            if (ModelState.IsValid)
            {
                try
                {
                    if (staff.ID > 0)
                    {
                        Staff tmpStaff = staffSrv.GetStaffById(staff.ID);
                        tmpStaff.FirstName = staff.FirstName;
                        tmpStaff.LastName = staff.LastName;
                        tmpStaff.Email = staff.Email;
                        tmpStaff.AddressLine1 = staff.AddressLine1;
                        tmpStaff.AddressLine2 = staff.AddressLine2;
                        tmpStaff.City = staff.City;
                        tmpStaff.County = staff.County;
                        tmpStaff.Country = staff.Country;
                        tmpStaff.Postcode = staff.Postcode;
                        tmpStaff.UpdatedDate = staff.UpdatedDate;
                        tmpStaff.Title = staff.Title;
                        tmpStaff.UpdatedDate = DateTime.Now;
                        staffSrv.UpdateStaff(tmpStaff);
                        ViewData["MSG"] = "Successfully updated the details.";
                    }
                    else
                    {
                        staffSrv.SaveStaff(staff);
                        ViewData["MSG"] = "Successfully saved the details.";
                    }

                    ModelState.Clear();
                    staff = new Staff();
                    model.Staff = staff;

                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "Error" + ex.ToString());
                }
            }

            IStaffService srv = new StaffServiceImpl();

            model.AllStaff = srv.GetAllStaffs();
            return RedirectToAction("Index"); ;
        }
        #endregion
    }
}
